import requests
import json
import jsonpath
import csv

url = 'https://shuyang.anjuke.com/v3/ajax/map/sale/1296/prop_list/?room_num=-1&price_id=-1&area_id=-1&floor=-1' \
      '&orientation=-1&is_two_years=0&is_school=0&is_metro=0&order_id=0&p=1&zoom=12&lat=34.008835_34.225933&lng=118' \
      '.258498_119.362336&kw=&maxp=99&et=5c7d91&ib=1&bst=pem254 '

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/86.0.4240.183 '
                  'Safari/537.36 '
}
responses = requests.get(url=url, headers=headers)

if responses.status_code == 200:
    try:
        jsons = json.loads(responses.content.decode())
        a = jsons
        region_name = jsonpath.jsonpath(a, "$.val.props")
        with open('沭阳房产.csv', 'w', encoding="utf-8") as f:

            for i in region_name:
                a = i
            for i in a:
                dicts = {}
                dicts['region_name'] = i['region_name']
                dicts['block_name'] = i['block_name']
                dicts['rhval'] = i['rhval']
                dicts['area'] = i['area']
                dicts['price'] = i['price']
                dicts['long_title'] = i['long_title']
                dicts['comm_name'] = i['comm_name']
                dicts['house_orient_name'] = i['house_orient_name']
                dicts['floor_tag'] = i['floor_tag']
                dicts = [dicts]
                f_csv = csv.DictWriter(f, ['region_name', 'block_name', 'rhval', 'area', 'price', 'long_title',
                                           'comm_name',
                                           'house_orient_name', 'floor_tag'])
                f_csv.writeheader()
                f_csv.writerows(dicts)
    except:
        print('出现错误，重新开启')
else:
    print('状态码不是200没有获取')
